
package com.jianzong.lingxuan.error;


import com.jianzong.lingxuan.base.Result;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import java.lang.reflect.UndeclaredThrowableException;
import java.util.HashMap;
import java.util.Map;

/**
 * @auth Leiwenlong
 * @since 2021/6/17
 */

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {


    /**
     * spring自带异常或自定义异常
     */
    @ExceptionHandler({
            MissingServletRequestParameterException.class,
            MethodArgumentTypeMismatchException.class,
            HttpRequestMethodNotSupportedException.class,
            UndeclaredThrowableException.class,
            BindException.class,
            IllegalArgumentException.class,
            CustomException.class
    })
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public Result logicException(Exception e) {
        String errorMessage;
        if (e instanceof UndeclaredThrowableException) {
            errorMessage = ((UndeclaredThrowableException) e).getUndeclaredThrowable().getMessage();
        } else if (e instanceof IllegalArgumentException) {
            return Result.error(405, e.getMessage());
        } else {
            errorMessage = e.getMessage();
        }

        return new Result.Builder().code(HttpStatus.BAD_REQUEST.value()).message(errorMessage).create();
    }

/*
    @ExceptionHandler(NullPointerException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Result unrecognizedHandler(Exception e) {
        return Result.error(SysError.SYSTEM_ERROR);
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleValidationExceptions(MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach((error) -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });
        return new Result.Builder()
                .code(SysError.PARAM_UNVALID.getCode())
                .data(errors)
                .create();
    }
*/

}

